package com.happy_hao.user.service.UserServiceImpl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.happy_hao.user.common.Result;
import com.happy_hao.user.dto.UpdateUserRequest;
import com.happy_hao.user.exception.ServiceException;
import com.happy_hao.user.mapper.*;
import com.happy_hao.user.po.*;
import com.happy_hao.user.service.AdministratorService;
import com.happy_hao.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AdministratorServiceImpl implements AdministratorService {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private GroupUserMapper groupUserMapper;

    @Resource
    private GroupPermissionMapper groupPermissionMapper;

    @Override
    public Result getAllUserSimpleInfo() {
        Map<String, Object> simpleUsers= new HashMap<>();
        List<String> usernames = getUsernames();
        simpleUsers.put("users",usernames);
        return Result.success().data(simpleUsers);
    }

    @Override
    public Result getUserInfo(String username) {
        return Result.success().data("user",userService.readUserByIdentifier(username).getData().get("user"));
    }

    @Override
    public Result updateUserInfoRequest(UpdateUserRequest updateUserRequest) {
        return userService.updateUser(updateUserRequest);
    }

    @Override
    public Result addNewGroup(String groupName) {
        QueryWrapper<Group> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_name", groupName);
        Group group = groupMapper.selectOne(queryWrapper);
        if (group != null) {
            throw new ServiceException("当前组名已被占用");
        }
        Group newGroup = new Group();
        newGroup.setGroupId(IdUtil.getSnowflakeNextId());
        newGroup.setGroupName(groupName);
        newGroup.setCreateAt(new Date());
        newGroup.setUpdateAt(newGroup.getCreateAt());
        groupMapper.insert(newGroup);
        return Result.success().message("创建"+groupName+"组成功");
    }

    @Override
    public Result getAllGroups() {
        List<Group> groups = groupMapper.selectList(null);
        if (groups == null) {
            return Result.success().message("操作成功但是未查询到任何组");
        }
        return Result.success().data("groups",groups);
    }

    @Override
    public Result bindUserToGroup(String groupName, String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", username);
        groupQueryWrapper.eq("group_name", groupName);
        User user = userMapper.selectOne(userQueryWrapper);
        Group group = groupMapper.selectOne(groupQueryWrapper);
        if(user == null){
            throw new ServiceException(username+"用户不存在");
        }
        if(group == null){
            throw new ServiceException(groupName+"组不存在");
        }
        Long groupId = group.getGroupId(),userId = user.getUserId();
        QueryWrapper<GroupUser> groupUserQueryWrapper = new QueryWrapper<>();
        groupUserQueryWrapper.eq("group_id", groupId).eq("user_id", userId);
        GroupUser groupUser = groupUserMapper.selectOne(groupUserQueryWrapper);
        if(groupUser != null){
            throw new ServiceException(username+"用户已经添加进"+groupName+"组，请不要重复添加");
        }
        GroupUser newGroupUser = new GroupUser();
        newGroupUser.setUserId(userId);
        newGroupUser.setGroupId(groupId);
        newGroupUser.setCreateAt(new Date());
        newGroupUser.setUpdateAt(newGroupUser.getCreateAt());
        groupUserMapper.insert(newGroupUser);
        return Result.success().message(username+"用户已经添加进"+groupName+"组");
    }

    @Override
    public Result kickUserFromGroup(String groupName, String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", username);
        groupQueryWrapper.eq("group_name", groupName);
        User user = userMapper.selectOne(userQueryWrapper);
        Group group = groupMapper.selectOne(groupQueryWrapper);
        if(user == null){
            throw new ServiceException(username+"用户不存在");
        }
        if(group == null){
            throw new ServiceException(groupName+"组不存在");
        }
        Long groupId = group.getGroupId(),userId = user.getUserId();
        QueryWrapper<GroupUser> groupUserQueryWrapper = new QueryWrapper<>();
        groupUserQueryWrapper.eq("group_id", groupId).eq("user_id", userId);
        GroupUser groupUser = groupUserMapper.selectOne(groupUserQueryWrapper);
        if(groupUser == null){
            throw new ServiceException(username+"用户不在"+groupName+"组");
        }
        groupUserMapper.delete(groupUserQueryWrapper);
        return Result.success().message("成功将"+username+"用户踢出"+groupName+"组");
    }

    @Override
    public Result getGroupAllUsers(String groupName) {
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("group_name", groupName);
        Group group = groupMapper.selectOne(groupQueryWrapper);
        if(group == null){
            throw new ServiceException(groupName+"组不存在");
        }
        Long groupId = group.getGroupId();
        QueryWrapper<GroupUser> groupUserQueryWrapper = new QueryWrapper<>();
        groupUserQueryWrapper.eq("group_id", groupId);
        List<GroupUser> groupUsers = groupUserMapper.selectList(groupUserQueryWrapper);
        if(groupUsers == null){
            throw new ServiceException(groupName+"组还没有绑定任何人");
        }
        List<Long> userIds = new ArrayList<>();
        for (GroupUser groupUser : groupUsers) {
            userIds.add(groupUser.getUserId());
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("user_id",userIds);
        List<User> users = userMapper.selectList(userQueryWrapper);
        return Result.success().message("操作成功").data("users",users);
    }

    @Override
    public Result getAllPermissions() {
        List<Permission> permissions = permissionMapper.selectList(null);
        if(permissions == null){
            throw new ServiceException("未查询到任何权限");
        }
        return Result.success().data("permissions",permissions);
    }

    @Override
    public Result bindPermissionToGroup(String groupName, String permissionName) {
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("group_name", groupName);
        Group group = groupMapper.selectOne(groupQueryWrapper);
        permissionQueryWrapper.eq("permission_name", permissionName);
        Permission permission = permissionMapper.selectOne(permissionQueryWrapper);
        if(group == null){
            throw new ServiceException(groupName+"组不存在");
        }
        if(permission == null){
            throw new ServiceException(permissionName+"权限不存在");
        }
        Long groupId = group.getGroupId(),permissionId = permission.getPermissionId();
        QueryWrapper<GroupPermission> groupPermissionQueryWrapper = new QueryWrapper<>();
        groupPermissionQueryWrapper.eq("group_id", groupId).eq("permission_id", permissionId);
        GroupPermission groupPermission = groupPermissionMapper.selectOne(groupPermissionQueryWrapper);
        if(groupPermission != null){
            throw new ServiceException(groupName+"组已经拥有了"+permissionName+"权限，请勿重复添加");
        }
        GroupPermission newGroupPermission = new GroupPermission();
        newGroupPermission.setGpId(IdUtil.getSnowflakeNextId());
        newGroupPermission.setGroupId(groupId);
        newGroupPermission.setPermissionId(permissionId);
        newGroupPermission.setCreateAt(new Date());
        newGroupPermission.setUpdateAt(newGroupPermission.getCreateAt());
        groupPermissionMapper.insert(newGroupPermission);
        return Result.success().message(groupName+"组拥有了"+permissionName+"权限");
    }

    @Override
    public Result dropPermissionFromGroup(String groupName, String permissionName) {
        QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("group_name", groupName);
        Group group = groupMapper.selectOne(groupQueryWrapper);
        permissionQueryWrapper.eq("permission_name", permissionName);
        Permission permission = permissionMapper.selectOne(permissionQueryWrapper);
        if(group == null){
            throw new ServiceException(groupName+"组不存在");
        }
        if(permission == null){
            throw new ServiceException(permissionName+"权限不存在");
        }
        Long groupId = group.getGroupId(),permissionId = permission.getPermissionId();
        QueryWrapper<GroupPermission> groupPermissionQueryWrapper = new QueryWrapper<>();
        groupPermissionQueryWrapper.eq("group_id", groupId).eq("permission_id", permissionId);
        GroupPermission groupPermission = groupPermissionMapper.selectOne(groupPermissionQueryWrapper);
        if(groupPermission == null){
            throw new ServiceException(groupName+"组尚未拥有"+permissionName+"权限");
        }
        groupPermissionMapper.delete(groupPermissionQueryWrapper);
        return Result.success().message("成功撤回权限");
    }

    public List<String> getUsernames() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_name");
        return userMapper.selectObjs(queryWrapper);
    }
}

